<template>
  <div class="illumination">
    <div class="title">安全校验配置</div>
    <div class="table-box">
      <Row>
        <Col span="12">
          <div class="select-box">
            <Cascader
              size="small"
              class="select-item"
              placeholder="区域"
              :data="cityList"
              v-model="model0"
              :disabled="true"
            ></Cascader>
            <Select
              :disabled="true"
              v-model="model1"
              size="small"
              class="select-item"
              placeholder="厂站"
            >
              <Option
                v-for="(item, index) in siteList"
                :value="item.siteId || ''"
                :key="item.siteId"
                >{{ item.siteName }}
              </Option>
            </Select>
            <Select
              :disabled="true"
              v-model="model2"
              size="small"
              class="select-item"
              placeholder="客户名称"
            >
              <Option
                v-for="(item, index) in userList"
                :value="item.custId || ''"
                :key="item.custName"
                >{{ item.custName }}
              </Option>
            </Select>
            <Select
              clearable
              v-model="model3"
              size="small"
              class="select-item"
              placeholder="设备类型"
            >
              <Option
                v-for="item in deviceList"
                :value="item.equipTypeNo || ''"
                :key="item.equipTypeNo"
                >{{ item.equipTypeName }}
              </Option>
            </Select>

            <Button
              @click="search"
              size="small"
              type="primary"
              style="padding: 0 10px;"
              >查询</Button
            >
            <!--<Button @click="reset" size="small" style="padding: 0 10px;">重置</Button>-->
          </div>
        </Col>
        <Col span="12">
          <div class="select-box" style="justify-content: flex-end">
            <Button
              :disabled="selections.length <= 0"
              @click="setSafeCheck(0)"
              size="small"
              type="info"
              style="margin-right:20px;padding: 0 10px;"
            >
              批量安全校验
            </Button>
            <Button
              :disabled="selections.length <= 0"
              @click="setSafeCheck(1)"
              size="small"
              type="info"
              style="margin-right:20px;padding: 0 10px;"
            >
              批量取消校验
            </Button>
            <Button
              :disabled="selections.length <= 0"
              @click="setSafeCheck(2)"
              size="small"
              type="info"
              style="margin-right:20px;padding: 0 10px;"
            >
              批量设置监护
            </Button>
            <Button
              :disabled="selections.length <= 0"
              @click="setSafeCheck(3)"
              size="small"
              type="info"
              style="padding: 0 10px;"
              >批量取消监护
            </Button>
          </div>
        </Col>
      </Row>

      <Table
        @on-selection-change="selectChange"
        border
        :columns="columns"
        :data="tableData"
        :loading="loading"
      ></Table>
    </div>
    <div class="pagination">
      <span
        >共{{ page.totalNum }}条记录 第{{ page.currentPage }}/{{
          Math.ceil(page.totalNum / page.pageSize) || 1
        }}页
      </span>
      <Page
        show-sizer
        @on-change="goPage"
        @on-page-size-change="goPageSize"
        :total="page.totalNum"
        :page-size="page.pageSize"
        :page-size-opts="page.pageSizeOpts"
        show-elevator
      />
    </div>
  </div>
</template>

<script>
import {
  getSafeCheckArea,
  getSafeCheckSite,
  getSafeCheckDeviceType,
  getSafeChecklist,
  updateControlcheck,
  updateControlDischeck,
  updateControlgua,
  updateControlDisgua,
  getAlarmOrgtree,
  selectBaseInfosByCustId,
  listEquipTypeNoPaging,
  getSubstationsAll,
  userControlList
} from "@/api/scada";

export default {
  name: "description",
  props: {},
  data() {
    return {
      cityList: [],
      siteList: [
        {
          value: "金星站",
          label: "金星站"
        }
      ],
      userList: [],
      deviceList: [],
      model0: [],
      model1: "",
      model2: "",
      model3: "",
      description: {},
      page: {
        currentPage: 1,
        pageSize: 5,
        totalNum: 0,
        pageSizeOpts: [5, 10, 15, 20]
      },
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        { title: "区域", key: "arename" },
        { title: "厂站", key: "zhangdian" },
        { title: "用户名称", key: "custname" },
        { title: "设备ID", key: "devid" },
        { title: "设备名称", key: "shebeiname" },
        {
          title: "是否安全校验",
          key: "ischeck",
          render: (h, params) => {
            return h("div", [h("span", ["否", "是"][params.row.ischeck])]);
          }
        },
        { title: "监护账号", key: "businessname" }
      ],
      tableData: [],
      dataOriginal: [],
      loading: false,
      selections: [],
      controlBasicInfo: {}
    };
  },
  computed: {},
  created() {},
  mounted: function() {
    getAlarmOrgtree().then((ret) => {
      const { code, result } = ret || {};
      if (code === 200) {
        const nextResult = result ? [result] : [];
        this.cityList = this.getTreeDataList(nextResult);
        this.model0 = this.setSelectedSite(this.cityList, this.controlBasicInfo.areaNo, [], false) || [];
        console.log(this.model0)
        sessionStorage.setItem("cityList", JSON.stringify(this.cityList));
      }
    });
    selectBaseInfosByCustId().then((res) => {
      if (res.code === 200) {
        this.userList = res.result || [];
      }
    });
    listEquipTypeNoPaging().then((res) => {
      if (res.code === 200) {
        this.deviceList = res.result || [];
      }
    });
    getSubstationsAll().then((res) => {
      if (res.code === 200) {
        this.siteList = res.result || [];
      }
    });

    this.controlBasicInfo = JSON.parse(
      sessionStorage.getItem("controlBasicInfo")
    );

    this.model1 = this.controlBasicInfo.siteId;
    this.model2 = this.controlBasicInfo.custId;

    // getSafeCheckDeviceType().then((res) => {
    //   const { code, result = [] } = res;
    //   if (code === 200) {
    //     result.forEach((item, index) => {
    //       this.deviceList.push({
    //         value: index,
    //         label: item
    //       });
    //     });
    //   }
    // });

    const { areaNo, siteId, custId } = this.controlBasicInfo;
    let checkListParams = {
      arenameno: areaNo,
      zhangdianid: siteId,
      custid: custId
    };
    this.getTableData(checkListParams);
  },
  watch: {},
  methods: {
    setSelectedSite(arr, areaNo, result = [], isChild = false) {
      if (!isChild) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].value === areaNo) {
            return result.push(areaNo);
          } else if (i === arr.length - 1) {
            return this.setSelectedSite(arr, areaNo, result, true);
          }
        }
      } else {
        for (let i = 0; i < arr.length; i++) {
          let child = arr[i].children;
          if (Array.isArray(child) && child.length > 0) {
            for (let j = 0; j < child.length; j++) {
              if (child[j].value === areaNo) {
                result.push(arr[i].value);
                result.push(areaNo);
                return result;
              } else if (j === child.length - 1) {
                result.push(arr[i].value);
                return this.setSelectedSite(child, areaNo, result, true);
              }
            }
          }
        }
      }
    },
    getTreeDataList(tree) {
      return tree.map((element) => {
        const { areaNo, areaName, children: prevChildren } = element;
        let children = [];
        if (Array.isArray(prevChildren) && prevChildren.length > 0) {
          children = this.getTreeDataList(prevChildren);
        }
        return {
          value: areaNo,
          label: areaName,
          children
        };
      });
    },
    getTableData(data = {}) {
        this.loading = true;
      getSafeChecklist(data).then((res) => {
        const { code, result = [] } = res;
        if (code === 200) {
          this.page.pageSize = 5;
          this.page.currentPage = 1;
          this.dataOriginal = result;
          this.page.totalNum = this.dataOriginal.length;
          this.initLamp();
        }
      }).finally(()=>{
          this.loading = false
      })
    },
    selectChange(selection) {
      this.selections = selection;
    },
    reset() {
      // this.model0 = ''
      // this.model1 = ''
      // this.model2 = ''
      this.model3 = "";
      this.getTableData();
    },
    search() {
      let data = {};
      if(this.model0 && Array.isArray(this.model0)) {
          data.arenameno = this.model0.slice(-1)[0]
      } else {
          data.arenameno = this.controlBasicInfo.arenameno
      }
      this.model1 && (data.zhangdianid = this.model1);
      this.model2 && (data.custid = this.model2);
      this.model3 && (data.shebeileixingno = this.model3);
      this.getTableData(data);
    },
    setSafeCheck(type) {
      // this.columns.unshift({
      //     type: 'selection',
      //     width: 60,
      //     align: 'center'
      // })
      let me = this;
      this.loading = true;
      let title, doAction;
      let data = [];
      let guauserid = JSON.parse(localStorage.getItem('admin')).sys.user["4"].user.info.sub
      if (type === 2 && guauserid) {
        data = this.selections.map((item) => {
          return { devid: item.devid, guauserid };
        });
      } else {
        data = this.selections.map((item) => {
          return { devid: item.devid };
        });
      }
      switch (type) {
        case 0:
          title = "请确认是否批量设置安全校验";
          doAction = updateControlcheck;
          break;
        case 1:
          title = "请确认是否批量取消安全校验";
          doAction = updateControlDischeck;
          break;

        case 2:
          title = "请确认是否批量设置监护";
          doAction = updateControlgua;

          break;
        case 3:
          title = "请确认是否批量取消监护";
          doAction = updateControlDisgua;
          break;
        default:
          break;
      }
      this.$Modal.confirm({
        title: "提示",
        content: title,
        onCancel:()=>{
            me.loading = false;
        },
        onOk: () => {
          doAction(data)
            .then((res) => {
              console.log(res);
            })
            .finally(() => {
              me.selections = [];
              me.loading = false;
              me.search();
            });
        }
      });
    },
    goPageSize(page) {
      this.page.pageSize = page;
      this.initLamp();
    },
    goPage(page) {
      this.page.currentPage = page;
      this.initLamp();
    },
    initLamp() {
      let start = this.page.pageSize * (this.page.currentPage - 1);
      let end = this.page.pageSize;
      this.tableData = this.dataOriginal.slice(start, start + end);
    }
  },
  components: {}
};
</script>

<style scoped lang="scss">
.illumination {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 5px;
  /*box-shadow: 2px 2px 4px 0px rgba(0, 0, 0, 0.13);*/
  .title {
    font-size: 16px;
    height: 40px;
    line-height: 40px;
    padding-left: 15px;
    color: #333;
    font-weight: 500;
    border-bottom: 1px solid #c7c7c7;
    position: relative;
    width: 100%;
  }
  .table-box {
    padding: 15px;
    .select-box {
      width: 100%;
      display: flex;
      padding-bottom: 15px;
      .select-item {
        width: 120px;
        margin-right: 10px;
      }
    }
  }
}

.illumination .pagination {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #c7c7c7;
  padding: 10px 15px;
}

.illumination .pagination span {
  font-size: 14px;
  font-family: SimSun;
  font-weight: 400;
  color: #666666;
}
</style>
<style lang="scss" scoped>
/deep/ .ivu-table-tip table tr td {
  text-align: center;
  background-image: url("~@/assets/img/zwsj.png");
  background-position: center 60px;
  background-repeat: no-repeat;
  color: #999;
  height: 369px;
  background-size: 190px;
  span {
    display: none;
  }
}
</style>
